<template>
  <base-content>
    <template>
      <sf-base-search ref="baseSearchEle" :base-searchs="baseSearchs" :base-handles="baseHandles" :base-data="baseFormData" />
      <sf-grid ref="grid" :columns="columns" :operations="operations" :store-config="configs" />
      <!-- 新建账号 -->
      <el-dialog title="新建帐号" :visible.sync="isShow" width="40%" :before-close="handleCancleCreate">
        <el-form ref="form" :model="form" label-width="180px">
          <el-form-item label="用户名">
            <el-col :span="14">
              <el-input v-model="form.account_name" placeholder="请输入用户名" />
            </el-col>
          </el-form-item>
          <el-form-item label="绑定的手机号">
            <el-col :span="14">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-col>
          </el-form-item>
          <el-form-item label="昵称">
            <el-col :span="14">
              <el-input v-model="form.user_name" placeholder="请输入昵称" />
            </el-col>
          </el-form-item>
          <el-form-item label="对应部门ID">
            <el-select v-model="form.dept_id" placeholder="请选择账号所属">
              <el-option v-for="item in selsAreas" :key="item.id" :label="item.dept_name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="!form.id" label="新密码">
            <el-col :span="14">
              <el-input v-model="form.password" type="password" placeholder="请输入新密码" />
            </el-col>
          </el-form-item>
          <el-form-item v-if="!form.id" label="确认新密码">
            <el-col :span="14">
              <el-input v-model="form.confirm_password" type="password" placeholder="再次输入新密码" />
            </el-col>
          </el-form-item>
          <el-form-item label="企业二维码">
            <el-col :span="20">
              <el-upload
                name="file"
                action="/api/api/admin/img/upload?type=1"
                :file-list="fileList"
                :headers="headers"
                :on-remove="handleRemove"
                :on-error="handleError"
                accept="image/png, image/jpeg, image/jpg"
                :on-success="handleSuccess"
                list-type="picture-card"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件
                </div>
              </el-upload>
            </el-col>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancleCreate">取 消</el-button>
          <el-button type="primary" @click="handleCreatAccount">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 重置密码 -->
      <el-dialog title="重置密码" :visible.sync="reSetShow" width="40%">
        <sf-base-form ref="resetPwd" width="300px" :eles="resetForm" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancelRestPwd">取 消</el-button>
          <el-button type="primary" @click="handleRestPwd">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </base-content>
</template>

<script>
import { queryParams, hasPermission } from '@/utils'
import { mapGetters } from 'vuex'
import { fetchCreateAccount, fetchUpdatePwd, fetchAccountList, fetchUpdateAccount, fetchAccountDetail } from '@/api/authority'
import { getDeptList } from '@/api/production-api'
import { apiUrl } from '@/utils/config'

export default {
  computed: {
    ...mapGetters(['sidebar']),
    routes() {
      return this.$router.options.routes
    }
  },
  data() {
    const token = localStorage.getItem('token')
    return {
      headers: { token },
      // here is dialog
      isShow: false,
      reSetShow: false,
      fileList: [],
      selsAreas: [],
      form: {
        id: '',
        wechat_img_url: '',
        account_name: '',
        dept_id: '',
        password: '',
        confirm_password: '',
        phone: '',
        user_name: ''
      },
      resetForm: [
        {
          label: '帐户ID',
          elType: 'input',
          readonly: true,
          placeholder: '',
          value: '',
          name: 'id'
        },
        {
          label: '新密码',
          elType: 'input',
          placeholder: '输入新密码',
          value: '',
          name: 'password'
        },
        {
          label: '确认新密码',
          elType: 'input',
          placeholder: '再次输入新密码',
          value: '',
          name: 'confirm_password'
        }
      ],
      baseSearchs: [
        {
          label: '账号昵称',
          elType: 'input',
          placeholder: '请输入用户名',
          value: '',
          name: 'user_name'
        },
        {
          label: '手机号',
          elType: 'input',
          placeholder: '请输入手机号',
          value: '',
          name: 'phone'
        }
      ],
      baseHandles: [
        {
          btnType: 'primary',
          text: '查询',
          key: 'search',
          handle: this.handleBaseSearch
        },
        {
          btnType: 'default',
          text: '重置',
          key: 'reset',
          handle: this.handleBaseSearch
        },
        {
          btnType: 'default',
          text: '新建帐号',
          key: 'add',
          handle: this.handleBaseSearch
        }
      ],
      baseFormData: {},
      formData: {},
      // here is table
      columns: [
        {
          title: 'id',
          props: 'id'
        },
        {
          title: '账号昵称',
          props: 'user_name'
        },
        {
          title: '绑定的手机号',
          props: 'phone'
        },
        {
          title: '账号类型',
          props: 'dept_type'
        },
        {
          title: '所属部门ID',
          props: 'dept_id'
        },
        {
          title: '所属部门名称',
          props: 'dept_name'
        }
      ],
      id: '',
      operations: [
        {
          label: '编辑',
          handler: (row) => {
            this.isShow = true
            fetchAccountDetail({ id: row.id }).then((result) => {
              if (result.code === '0') {
                const data = result.info.data
                this.fileList = [{ url: `${apiUrl}${data.wechat_img_url}` }]
                this.form = data
              } else {
                this.$message.error(`查询失败：${result.msg}`)
              }
            })
          }
        },
        {
          label: '重置密码',
          handler: (row) => {
            const { id } = row
            this.id = id
            this.reSetShow = true
            this.$nextTick(() => {
              this.$refs.resetPwd.setVal({ id })
            })
          }
        }
      ],
      configs: {
        loadDataApi: (p) => {
          return new Promise((resolve) => {
            fetchAccountList(queryParams(p, this.formData)).then((res) => {
              resolve(res)
            })
          })
        },
        fetchListData: function (res) {
          return res.info.data
        },
        fetchTotal: function (res) {
          return res.info.meta.count
        },
        generateQueryParams: function (pagination) {
          const { pageIndex, pageSize } = pagination
          return {
            page_size: pageSize,
            page_num: pageIndex
          }
        }
      }
    }
  },
  async mounted() {
    const result = await getDeptList()
    if (result.code === '0') {
      this.selsAreas = result.info.data
    } else {
      this.selsAreas = []
    }
    const isHidden = !hasPermission('权限管理')
    if (isHidden) {
      this.operations = []
      this.baseHandles = this.baseHandles.filter((item) => item.key !== 'add')
    }
  },
  methods: {
    handleCancleCreate() {
      this.isShow = false
      this.handleClearCatch()
      this.fileList = []
      this.form = {
        id: '',
        wechat_img_url: '',
        account_name: '',
        dept_id: '',
        password: '',
        confirm_password: '',
        phone: '',
        user_name: ''
      }
    },
    handleCancelRestPwd() {
      this.reSetShow = false
      this.handleClearCatch()
    },
    handleClearCatch() {
      this.$refs.createAccountForm ? this.$refs.createAccountForm.empty() : ''
      this.$refs.resetPwd ? this.$refs.resetPwd.empty() : ''
    },
    handleRestPwd() {
      const val = this.$refs.resetPwd.getVal()
      val.id = this.id
      fetchUpdatePwd(val).then((res) => {
        this.reSetShow = false
        this.handleClearCatch()
      })
    },
    async handleCreatAccount() {
      const val = this.form
      if (!val.account_name) {
        return this.$message.error('请输入用户名')
      }
      if (!val.phone) {
        return this.$message.error('请输入手机号')
      }
      const phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/
      if (!phoneReg.test(val.phone)) {
         return this.$message.error('请输入正确手机号')
      }
      if (!val.user_name) {
        return this.$message.error('请输入昵称')
      }
      if (!val.dept_id) {
        return this.$message.error('请输入选择对应部门ID')
      }
      if (!val.id && !val.password) {
        return this.$message.error('请输入新密码')
      }
      if (!val.id && val.password !== val.confirm_password) {
        return this.$message.error('两次密码不一致请重新输入')
      }
      if (!val.wechat_img_url) {
        return this.$message.error('请上传企业二维码')
      }
      if (val.id) {
        const res = await fetchUpdateAccount(val)
          if (res.code === '0') {
          this.$message.success('修改成功')
          this.isShow = false
          this.$refs.grid.query()
          this.handleClearCatch()
        } else {
          this.$message.error('修改失败：' + res.msg)
        }
      } else {
        const res = await fetchCreateAccount(val)
        if (res.code === '0') {
          this.$message.success('创建成功')
          this.isShow = false
          this.$refs.grid.query()
          this.handleClearCatch()
        } else {
          this.$message.error('创建失败：' + res.msg)
        }
      }
    },
    // 图片上传失败 回调
    handleError(err, file, fileList) {
      this.$message.error(`上传失败：${err.msg}`)
    },
    // 删除图片回调
    handleRemove(file, fileList) {
      this.fileList = []
      this.form.wechat_img_url = ''
    },
    // 图片上传成功 回调
    handleSuccess(result, file, fileList) {
      if (result.code === '0001') {
        this.$message.error(`上传失败：${result.msg}`)
        this.fileList = []
      } else if (result.code === '9999') {
        window.location.href = '/#/login'
      } else {
        this.fileList = [file]
        this.$message.success('上传成功')
        this.form.wechat_img_url = result.info.data
      }
    },
    // val: 当前表单中的数据
    // key 用来handles 中设置的唯一标识key值
    handleBaseSearch(val, key) {
      if (key === 'search') {
        this.formData = val
        this.$refs.grid.query()
      } else if (key === 'add') {
        this.isShow = true
      } else {
        const formEle = this.$refs.baseSearchEle
        formEle.empty()
        this.$refs.grid.query()
      }
    }
  }
}
</script>
